/*******************************************************************************
 * Copyright 2011-2012 Dik Grapendaal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package sh.grapendaal.tsuushin.socket;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.util.CharsetUtil;

public class IrcSocketFactory {
	private static ChannelFactory factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool());

	/**
	 * Static class.
	 */
	private IrcSocketFactory() {}
	
	/**
	 * Creates a new IrcSocket which connects to the given internet socket
	 * address.
	 * 
	 * @param server
	 *            The server to connect to.
	 * @return IrcSocket object on which one or more listeners can be added.
	 */
	public static IrcSocket createSocket(InetSocketAddress server) {
		ClientBootstrap bootstrap = new ClientBootstrap(factory);
		bootstrap.getPipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
		bootstrap.getPipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
		bootstrap.getPipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

		return new IrcSocket(bootstrap, server);
	}
	
	/**
	 * Shuts down the NIO socket channel factory.
	 */
	public static void shutdown() {
		factory.releaseExternalResources();
	}
}
